package com.yinhai.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.listener.MsgTextLongClickListener;
import com.yinhai.adapter.ContactAdpter;
import com.yinhai.cfg.AppConfig;
import com.yinhai.constant.ChatConstant;
import com.yinhai.constant.Contact;
import com.yinhai.model.MsgModel;
import com.yinhai.model.UserUserContact;
import com.yinhai.service.ContactUserServiceImpl;

/**
 * 消息界面选择集团通讯录人员
 * 
 * @author lixh
 *
 */
public class ContactGroupAcitivty extends Activity implements OnScrollListener {
	private ListView groupListView;
	private ContactAdpter smsAdpter;
	private ContactUserServiceImpl contactUserService;
	private EditText editText;
	private CheckBox checkBox;
	private boolean checked = false;
	private boolean isGroup = true;
	private ImageView head_btn_back;
	private String groupId = null;

	private View progressView;
	private int visibleLastIndex = 0; // 最后的可视项索引
	private int visibleItemCount; // 当前窗口可见项总数

	MsgModel resendMsgModel;

	List<UserUserContact> groupUserlist = new ArrayList<UserUserContact>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_contact);
		if (getIntent().hasExtra(MsgTextLongClickListener.SER_KEY)) {
		    resendMsgModel=(MsgModel)getIntent().getSerializableExtra(MsgTextLongClickListener.SER_KEY);
        }
		TextView titleView = (TextView) this.findViewById(R.id.txt_contact);
		titleView.setText("选择人员");
		View loadMoreView = LayoutInflater.from(this).inflate(
				R.layout.load_more, null);
		progressView = loadMoreView.findViewById(R.id.pg);

		editText = (EditText) this.findViewById(R.id.search_txt);
		checkBox = (CheckBox) this.findViewById(R.id.search_cb);
		groupListView = (ListView) this
				.findViewById(R.id.contact_group_list_item);
		head_btn_back = (ImageView) this.findViewById(R.id.head_btn_back);
		head_btn_back.setVisibility(View.VISIBLE);
		checkBox.setVisibility(View.GONE);
		contactUserService = new ContactUserServiceImpl(this);
		smsAdpter = new ContactAdpter(this);

		smsAdpter.addCollection(ClearSelf(contactUserService.searchContactUser(
				null, getIntent().getStringExtra("groupID"),null)));

		groupListView.addFooterView(loadMoreView);
		groupListView.setOnScrollListener(this);

		groupListView.setAdapter(smsAdpter);

		groupListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				UserUserContact userContact = (UserUserContact) smsAdpter
						.getItem(position);
				Intent intent = new Intent(ContactGroupAcitivty.this,
						ChatActivity.class);
				intent.putExtra("receID", userContact.getPhone());
				intent.putExtra("receName", userContact.getName());
				intent.putExtra("type", 1);// 1:一对一；2：部门；3：群组
				ChatConstant.CURRENT_CHAT = "1";
				ChatConstant.CURRENT_CHART_ID = userContact.getPhone();
                if (resendMsgModel != null) {
                    Bundle mBundle = new Bundle();
                    mBundle.putSerializable(MsgTextLongClickListener.SER_KEY, resendMsgModel);
                    intent.putExtras(mBundle);
                }
				startActivity(intent);
				finish();

			}
		});
		editText.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable arg0) {
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void onTextChanged(CharSequence s, int arg1, int arg2,
					int arg3) {
				String content = s.toString();
				if (checked) {
					// 选中查询部门 查询部门数据
					if ((content != null) && (!"".equals(content))) {
						initGroupData(content);
					} else {
						// 判断之前是部门数据分组还是其他
						if (isGroup) {
							initGroupData(null);
						} else {
							initUserContactData(null, groupId);
						}
					}

				} else {
					// 查询联系人数据
					if ((content != null) && (!"".equals(content))) {
						initUserContactData(content, groupId);
					} else {
						// 判断之前是部门数据分组还是其他
						if (isGroup) {
							initGroupData(null);
						} else {
							initUserContactData(null, groupId);
						}
					}

				}
			}

		});
		//
		checkBox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton button,
					boolean isChecked) {
				checked = isChecked;
			}

		});
		head_btn_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View ediview) {
				onBackPressed();
			}
		});
	}

	/**
	 * 初始化分组数据
	 */
	private void initGroupData(String content) {
		smsAdpter.removeAll();
		smsAdpter.notifyDataSetChanged();
		smsAdpter.addCollection(ClearSelf(contactUserService
				.searchGroup(content)));
		smsAdpter.notifyDataSetChanged();
		// head_btn_back.setVisibility(View.VISIBLE);
		checkBox.setVisibility(View.VISIBLE);
	}

	private void initUserContactData(String content, String groupId) {
		smsAdpter.removeAll();
		smsAdpter.notifyDataSetChanged();
		smsAdpter.addCollection(ClearSelf(contactUserService.searchContactUser(
				content, groupId,null)));
		smsAdpter.notifyDataSetChanged();
		head_btn_back.setVisibility(View.VISIBLE);
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		this.visibleItemCount = visibleItemCount;
		visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		int itemsLastIndex = smsAdpter.getCount() - 1; // 数据集最后一项的索引
		int lastIndex = itemsLastIndex + 1; // 加上底部的loadMoreView项
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
				&& visibleLastIndex == lastIndex) {
			progressView.setVisibility(View.VISIBLE);
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					loadMore();
				}

			}, 2000);
		}
	}

	private void loadMore() {
		if (!isGroup) {
			List<UserUserContact> list = contactUserService.searchContactUser(
					null, Contact.CONTACT_TYPE_ONLINE,null);
			smsAdpter.addCollection(ClearSelf(list));

			smsAdpter.notifyDataSetChanged(); // 数据集变化后,通知adapter
			groupListView.setSelection(visibleLastIndex - visibleItemCount + 1); // 设置选中项
			progressView.setVisibility(View.GONE);
		}

	}

	public List<UserUserContact> ClearSelf(List<UserUserContact> listUser) {
		SharedPreferences preferences = getSharedPreferences(
				AppConfig.LOGIN_CONFIG, Context.MODE_PRIVATE);
		String phone = preferences.getString("name", "");
		if (listUser.size() > 0) {
			for (int i = 0; i < listUser.size(); i++) {
				if (listUser.get(i).getPhone().indexOf(phone) > -1) {
					listUser.remove(i);
					break;
				}
			}
		}
		return listUser;
	}

}
